package com.xt.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xt.back.entity.User;
import com.xt.back.exception.OperateException;
import com.xt.back.mapper.UserMapper;
import com.xt.back.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xt.back.utils.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author leotong
 * @since 2022-04-03
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    @Override
    public String login(User user) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserName,user.getUserName());
        User result = this.getOne(queryWrapper);
        if (result==null){
            throw new OperateException("当前用户不存在");
        }
        if (!result.getPassword().equals(user.getPassword())){
            throw new OperateException("密码输入错误");
        }
        if (result.getStatus().equals("1")){
            throw new OperateException("当前用户被停用");
        }
        return TokenUtil.createToken("admin:1");
    }

    @Override
    public Page<User> getUserByPage( User user) {
        Page<User> page=new Page<>(user.getPageNum(),user.getPageSize());
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().like(user.getUserName()!=null&&!Objects.equals(user.getUserName(),""),User::getUserName,user.getUserName())
                .eq(user.getUserType()!=null&&!Objects.equals(user.getUserType(),""),User::getUserType,user.getUserType())
                .eq(user.getStatus()!=null&&!Objects.equals(user.getStatus(),""),User::getStatus,user.getStatus())
                .like(user.getSex()!=null&&!Objects.equals(user.getSex(),""),User::getSex,user.getSex());
        return userMapper.selectPage(page,queryWrapper);
    }
}
